/*
 * @lc app=leetcode.cn id=124 lang=cpp
 *
 * [124] 二叉树中的最大路径和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
    int ans = INT_MIN;
    int maxPathSum2(TreeNode *root)
    {
        int l = INT_MIN, r = INT_MIN;
        if (root->left)
            l = maxPathSum(root->left);
        if (root->right)
            r = maxPathSum(root->right);

        if (r > l && r > 0)
        {
            ans = std::max(ans, r);
            return r + root->val;
        }
        else if (l > r && l > 0)
        {
            ans = std::max(ans, l);
            return l + root->val;
        }
        else
        {
            ans = std::max(root->val, ans);
            return root->val;
        }
    }

public:
    int maxPathSum(TreeNode *root)
    {
        ans = root->val;
        int l = INT_MIN, r = INT_MIN;
        if (root->left)
        {
            l = maxPathSum2(root->left);
        }
        if (root->right)
        {
            r = maxPathSum2(root->right);
        }

        return ans;
    }
};
// @lc code=end
